﻿using System;
using System.Data;
using CRM.Anyleads;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class AnyleadsClientApplicationCollectionExtensions
    {
        public static void AddAnyleadsClient(this IServiceCollection service, string apiKey)
        {
            service.AddHttpClient();
            service.TryAddTransient(provider => ActivatorUtilities.CreateInstance<AnyleadsClient>(provider, apiKey));
        }

        /// <summary>
        /// 添加Anyleads客户端
        /// </summary>
        /// <param name="service"></param>
        /// <param name="func"></param>
        /// <exception cref="NoNullAllowedException"></exception>
        public static void AddAnyleadsClient(this IServiceCollection service, Action<AnyleadsOption> func)
        {
            service.AddHttpClient();

            AnyleadsOption option = new AnyleadsOption();
            func(option);
            if (string.IsNullOrEmpty(option.ApiKey)) throw new NoNullAllowedException("Anyleads:apiKey不能为空");
            
            service.TryAddTransient(provider =>
            {
                return ActivatorUtilities.CreateInstance<AnyleadsClient>(provider, option);
            });
        }
    }
}